from forms import *
from datetime import datetime

class VotePage(webapp.RequestHandler):
  def post(self):
    poll = None
    if users.get_current_user():
      choice_key = self.request.get("choice")
      if choice_key:
        choice = Choice.get(choice_key)
        poll = choice.poll
        error_message = ""
        res = Vote.gql('WHERE owner = :owner AND poll = :poll', 
                        owner=users.get_current_user(),
                        poll=poll).count()
        if res <> 0:
          error_message = "You have already voted for this poll !"
        elif poll.end_date and poll.end_date < datetime.today():
          error_message = "You can't vote. Poll closed on %s" % poll.end_date.strftime("%Y-%m-%d")
        else:
          vote = Vote(owner = users.get_current_user(), choice = choice, poll = poll)
          vote.put()
        url = users.create_logout_url(self.request.uri)
        url_linktext = 'Logout'
      else:
        url = users.create_logout_url(self.request.uri)
        url_linktext = 'Logout'
        error_message = "Don't be stupid! Select a choice"
        self.redirect('/')
    else:
      url = users.create_login_url(self.request.uri)
      error_message = "You must be <a href='%s'>logged in</a> to vote!" % url

    template_values = {
      'url' : url,
      'url_linktext': url_linktext,
      'error_message' : error_message,
      'poll': poll
    }
    path = os.path.join(os.path.dirname(__file__), 'result.html')
    self.response.out.write(template.render(path, template_values))

